﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using System.Web.Routing;
using System.Collections.Specialized;

using Microsoft.Practices.Unity;

using ERPStore.Services;
using ERPStore.Extensions;

using ERPStore.Web.Html;
using ERPStore.Web.Routing;
using ERPStore.Web.Extensions;

using CloudSoft.Extensions;
using System.Threading.Tasks;

namespace ERPStore.Web.Controllers
{
	public partial class CatalogController
	{
		[ActionFilters.TrackerActionFilter]
		public ActionResult Brand(string link)
		{
			if (link.IsNullOrTrimmedEmpty())
			{
				Logger.Warn("brand without link");
				return RedirectToERPStoreRoute(ERPStoreRoutes.HOME);
			}
			// link = link.Replace("_", " ");
			var brand = CatalogService.GetBrandByLink(link);
			if (brand == null)
			{
				return RewriterService.RewriteUrl(Request);
			}

			var filter = CatalogService.CreateProductListFilter(HttpContext.GetWebContextParameterList());
			filter.BrandId = brand.Id;

			var result = GetProductList(filter);

			// Dans le cas ou le numéro de page n'exise plus
			// On retourne sur la premiere page 
			if (result != null
				&& result.Count == 0
				&& result.PageIndex > 1)
			{
				var url = Request.RawUrl.RemoveParameter(ERPStore.GlobalConfiguration.Configuration.Settings.Catalog.PageParameterName);
				return Redirect(url);
			}

			if (result != null
				&& result.Count == 0)
			{
				return RewriterService.RewriteBrandUrl(brand, Url);
			}

			result.Brand = brand;
			result.ListType = ERPStore.Models.ProductListType.Brand;
			ViewBag.ProductListFilter = filter;

			EventPublisherService.PublishAsync(new Events.ProductListEvent(User, result, ERPStore.Models.ProductListType.Brand));

			ViewData.Model = result;
			return View();
		}

		[ActionFilters.TrackerActionFilter]
		public ActionResult BrandList()
		{
			var key = "BrandList";
			var list = CacheService[key] as IList<ERPStore.Models.Brand>;
			if (list == null)
			{
				list = CatalogService.GetBrands().OrderBy(i => i.Name).ToList();
				CacheService.Add(key, list, DateTime.Now.AddHours(1));
				Logger.Debug("Brand list in cache");
			}
			ViewData.Model = list;
			return View();
		}

		#region Partial rendering

		// [ActionFilters.PartialRenderActionFilter(Order=1)]
		// [ActionFilters.CacheActionFilter(CacheKey = "BrandList", Duration = 3600, VaryByParam="*")]
		public ActionResult ShowBrandListView(string brandViewName)
		{
			var list = CatalogService.GetBrands();
			ViewData.Model = list;
			return PartialView(brandViewName);
		}

		/// <summary>
		/// Shows the brand list forefront.
		/// </summary>
		/// <param name="viewName">Name of the view.</param>
		/// <param name="routeData">The route data.</param>
		/// <returns></returns>
		// [ActionFilters.PartialRenderActionFilter(Order=1)]
		// [ActionFilters.CacheActionFilter(CacheKey = "BrandListForefront", Duration = 3600)]
		public ActionResult ShowBrandListForefront(string viewName, System.Web.Routing.RouteData routeData)
		{
			var list = CatalogService.GetBrandListForefront().ToList();

			return PartialView(viewName, list);
		}

		// [ActionFilters.CacheActionFilter(CacheKey = "BrandListByProductCategory", Duration = 3600, VaryByParam="*")]
		// [OutputCache(Duration=3600, VaryByParam="*")]
		public ActionResult ShowBrandListByProductCategory(ERPStore.Models.ProductCategory productCategory, string viewName)
		{
			var searchFilter = CatalogService.CreateProductListFilter(HttpContext.GetWebContextParameterList());

			searchFilter.ProductCategoryId = productCategory.Id;

			var list = CatalogService.GetBrandListBySearch(searchFilter);
			ViewData.Model = list;
			return PartialView(viewName);
		}

		public ActionResult ShowBrandListBySearch(string viewName, string search)
		{
			if (!search.IsNullOrTrimmedEmpty())
			{
				search = search.Trim();
			}

			var searchFilter = CatalogService.CreateProductListFilter(HttpContext.GetWebContextParameterList());

			searchFilter.Search = search;

			var category = CatalogService.GetCategoryByCode(Request["category"]);
			if (category != null)
			{
				searchFilter.ProductCategoryId = category.Id;
			}

			var list = CatalogService.GetBrandListBySearch(searchFilter);
			ViewData.Model = list;
			return PartialView(viewName);
		}

		public ActionResult ShowFilteredBrandListByProductList(string viewName, string filter, string currentUrl)
		{
			if (viewName.IsNullOrTrimmedEmpty()
				|| filter.IsNullOrTrimmedEmpty())
			{
				return new EmptyResult();
			}

			var jsonfilter = filter.UnGZipFromBase64String();
			var f = jsonfilter.FromJSon<ERPStore.Models.ProductListFilter>();

			currentUrl = currentUrl ?? string.Empty;
			ViewBag.CurrentUrl = currentUrl.Replace("&amp;", "&");
			var parameters = new Uri("http://url" + currentUrl).GetParameters();
			ViewBag.Parameters = parameters;
			ViewBag.CurrentFilter = f;

			var key = string.Format("brandlistfilter:{0}", filter);
			var list = CacheService[key] as IList<ERPStore.Models.Brand>;
			if (list == null)
			{
				list = CatalogService.GetBrandListBySearch(f);
				CacheService.Add(key, list, DateTime.Now.AddHours(1));
			}

			ViewData.Model = list;
			return PartialView(viewName);
		}

		[OutputCache(Duration=600, VaryByParam="*")]
		public async Task<ActionResult> ShowBrandListByProductList(string viewName, ERPStore.Models.ProductListFilter filter)
		{
			if (!filter.Search.IsNullOrTrimmedEmpty())
			{
				filter.Search = filter.Search.Trim();
			}

			var list = await Task.Run<IList<ERPStore.Models.Brand>>(() =>
				{
					return CatalogService.GetBrandListBySearch(filter);
				});
			ViewData.Model = list;
			return PartialView(viewName);
		}

		#endregion


	}
}
